﻿using com.iot.core.infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.iot.core.util
{
    public class FileUtil
    {
        public static string GetContentType(string path,string pdefault="")
        {
            var provider = new FileExtensionContentTypeProvider();
            string contentType;
            if (!provider.TryGetContentType(path, out contentType))
            {
                contentType = pdefault;// "image/jpeg";// "application/octet-stream";
            }
            return contentType??"";
        }

        public static async Task SaveAsync(string dir,string fname,string data)
        {
            string appPath = CommonHelper.DefaultFileProvider.AppPath;
            if (!string.IsNullOrWhiteSpace(dir))
            {
                var arrDir = dir.Split('/', StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in arrDir)
                {
                    appPath=Path.Combine(appPath, item);
                    if (!Directory.Exists(appPath))
                    {
                        Directory.CreateDirectory(appPath);
                    }
                }
            }
            var fullname = Path.Combine(appPath, fname);
            await File.WriteAllTextAsync(fullname,data,Encoding.UTF8);             
        }


        public static async Task<string> GetAsync(string dir, string fname)
        {
            string appPath = CommonHelper.DefaultFileProvider.AppPath;
            if (!string.IsNullOrWhiteSpace(dir))
            {
                var arrDir = dir.Split('/', StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in arrDir)
                {
                    appPath = Path.Combine(appPath, item);
                    if (!Directory.Exists(appPath))
                    {
                        return "";
                    }
                }
            }
            var fullname = Path.Combine(appPath, fname);
            if (!File.Exists(fullname))
            {
                return "";
            }
            return await File.ReadAllTextAsync(fullname, Encoding.UTF8);
        }

    }
}
